/*Author: Rony Lahav (ID:043489889)*/

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;


public class DisconnectedSNHandler implements Runnable{
	
	private DBTuple sn;
	private long uniqueID;
	private static DatagramSocket ds = final_project.mainUDPSoc;
	
	public DisconnectedSNHandler(DBTuple sn, long id){
		this.sn=sn;
		uniqueID=id;
		DataBase.getInstance().disconnectSNsOfOfflineSN(sn);
	}
	
	public void run(){
		DBTuple snToContact = DataBase.getInstance().getNextUnconnectedSNTuple();
		while (snToContact != null){
			String msg = "#" + MessageCenter.getInstance().createMessage_SNLIST_ForSNs(false);
			UDPSend(snToContact, msg);
			try {
				//in this time the UDPListener will process incoming SNLIST from this SN if he replies with one 
				Thread.sleep(final_project.timeout);
			} catch (InterruptedException e) {}
			snToContact = DataBase.getInstance().getNextUnconnectedSNTuple();
		}
		DataBase.getInstance().clearUnconnectedList();
		final_project.removeThreadFromLivingList(uniqueID);
	}
	
	private static void UDPSend(DBTuple tupleForSending, String msg) {
		try {
			if (!final_project.isShutDown()){
				DatagramPacket dp = new DatagramPacket(msg.getBytes(), msg.length(), InetAddress.getByName(tupleForSending.getPeerIP()),Integer.parseInt(tupleForSending.getUdpPort()));
				ds.send(dp); // send the message to the peer
			}
		}
		catch (SocketTimeoutException e1){
			if (ds != null && !ds.isClosed()){
				ds.close();
			}
		} catch (IOException e) {}
	}

}
